#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com


from django.shortcuts import render, redirect
from webadmin.views_dir import pub

from webadmin import models
from django.http import JsonResponse

from datetime import datetime
from webadmin.views_dir.mongo_oper import get_db_obj
from bson.objectid import ObjectId

from webadmin.forms import ArticleForm


# 文章管理
@pub.is_login
def article_management(request):

    article_objs = get_db_obj().articles.find()

    # 所有用户的信息
    user_data = {}
    for i in get_db_obj().user.find({}, {"_id": 1, "username": 1}):
        user_data[i["_id"]] = i["username"]

    return render(request, 'webadmin/article/article_management.html', locals())


@pub.is_login
def article_management_oper(request, oper_type, o_id):

    user_id = request.session['user_id']
    response = pub.BaseResponse()

    if request.method == "POST":
        # 添加
        if oper_type == "add":
            tag = request.POST.get('tag')

            form_obj = ArticleForm(request.POST)

            if form_obj.is_valid():
                get_db_obj().articles.insert({
                    "_id": str(ObjectId()),
                    "column_id": form_obj.cleaned_data["column_id"],
                    "title": form_obj.cleaned_data["title"],
                    "tag": tag,
                    "show": form_obj.cleaned_data["show"],
                    "content": form_obj.cleaned_data["content"],
                    "create_date": datetime.now(),
                })

                for i in tag.split(','):
                    t_obj = get_db_obj().tags.find_one({"name": i.strip()})
                    if not t_obj:
                        get_db_obj().tags.insert({
                            "_id": str(ObjectId()),
                            "name": i.strip(),
                            "hit": 0,  # 命中次数,表示有多少人点击了这个标签
                            "create_user_id": user_id,
                            "create_date": datetime.now()
                        })

                response.statusCode = 200
                response.message = "文章添加成功"
            else:
                for i in ["column_id", "title", "show", "content"]:
                    if i in form_obj.errors:
                        response.statusCode = 300
                        print(form_obj.errors.as_json())
                        response.message = form_obj.errors[i][0]

                        break

        # 修改
        elif oper_type == "update":

            tag = request.POST.get('tag')

            form_obj = ArticleForm(request.POST)

            if form_obj.is_valid():
                get_db_obj().articles.update({"_id": o_id}, {
                    "column_id": form_obj.cleaned_data["column_id"],
                    "title": form_obj.cleaned_data["title"],
                    "tag": tag,
                    "show": form_obj.cleaned_data["show"],
                    "content": form_obj.cleaned_data["content"],
                    "create_date": datetime.now(),
                })

                for i in tag.split(','):
                    t_obj = get_db_obj().tags.find_one({"name": i.strip()})
                    if not t_obj:
                        get_db_obj().tags.insert({
                            "_id": str(ObjectId()),
                            "name": i.strip(),
                            "hit": 0,  # 命中次数,表示有多少人点击了这个标签
                            "create_user_id": user_id,
                            "create_date": datetime.now()
                        })

                response.statusCode = 200
                response.message = "文章修改成功"
            else:
                for i in ["column_id", "title", "show", "content"]:
                    if i in form_obj.errors:
                        response.statusCode = 300
                        print(form_obj.errors.as_json())
                        response.message = form_obj.errors[i][0]

            # 删除
        elif oper_type == "del":
            get_db_obj().articles.remove({"_id": o_id})

            response.statusCode = 200
            response.message = "删除成功"
            response.callbackType = None


        return JsonResponse(response.__dict__)

    else:
        columns_list = get_db_obj().columns.find({}, {"_id": 1, "name": 1})

        # 添加
        if oper_type == "add":

            return render(request, 'webadmin/article/article_management_modal_add.html', locals())

        # 修改
        elif oper_type == "update":
            article_obj = get_db_obj().articles.find_one({"_id": o_id})
            return render(request, 'webadmin/article/article_management_modal_update.html', locals())

        # 预览
        elif oper_type == "preview":
            article_obj = get_db_obj().articles.find_one({"_id": o_id})

            return render(request, 'webadmin/article/article_management_modal_preview.html', locals())